package com.tongcheng.edu.util;


import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.cglib.core.Converter;

import java.math.BigDecimal;
import java.util.Map;

public class BeanUtils {

    private static Logger logger = LoggerFactory.getLogger(BeanUtils.class);
    private static Map<String, BeanCopier> copierMap = Maps.newHashMap();
    private static BeanUtils.PropertyConverter propertyConverter = new BeanUtils.PropertyConverter();

    public BeanUtils() {
    }

    public static void copyProperties(Object src, Object dest) {
        try {
            String key = src.getClass().getName() + dest.getClass().getName();
            BeanCopier copier;
            if (copierMap.containsKey(key)) {
                copier = (BeanCopier)copierMap.get(key);
            } else {
                copier = BeanCopier.create(src.getClass(), dest.getClass(), true);
                copierMap.put(key, copier);
            }

            copier.copy(src, dest, propertyConverter);
        } catch (Exception var4) {
            var4.printStackTrace();
            logger.error("属性复制发生异常!", var4);
        }

    }

    private static class PropertyConverter implements Converter {
        private PropertyConverter() {
        }

        public Object convert(Object value, Class target, Object context) {
            if (value == null) {
                return null;
            } else {
                try {
                    if (!value.getClass().equals(target)) {
                        if (target.equals(BigDecimal.class)) {
                            return new BigDecimal(value.toString());
                        }

                        if (target.equals(Long.class)) {
                            return Long.valueOf(value.toString());
                        }

                        if (target.equals(Integer.class)) {
                            return Integer.valueOf(value.toString());
                        }

                        if (target.equals(Integer.TYPE)) {
                            return Integer.valueOf(value.toString());
                        }

                        if (target.equals(String.class)) {
                            return value.toString();
                        }
                    }

                    return value;
                } catch (Exception var5) {
                    BeanUtils.logger.error("src value:[{}],target class:[{}]类型转换错误", new Object[]{value, target, var5});
                    return null;
                }
            }
        }
    }
}
